<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主表名称" prop="masterTableName">
        <el-input
          v-model="queryParams.masterTableName"
          placeholder="请输入主表名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lc:biz:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lc:biz:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lc:biz:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lc:biz:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="代码" align="center" prop="code" />
      <el-table-column label="名称" align="center" prop="title" />
      <el-table-column label="组件路径" align="center" prop="componentUrl" />
      <el-table-column label="主表名称" align="center" prop="masterTableName" />
      <el-table-column label="绑定工作流" align="center" prop="workflowDefineId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lc:biz:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lc:biz:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业务类型对话框 -->
    <el-dialog :title="title" v-if = "open" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主表名称" prop="masterTableName">
              <el-input v-model="form.masterTableName" placeholder="请输入主表名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联主键" prop="主键字段">
              <el-input v-model="form.idField" placeholder="请输入主键字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联属性" prop="主键字段">
              <el-input v-model="form.idProps" placeholder="请输入主键字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示字段" prop="显示字段">
              <el-input v-model="form.showField" placeholder="请输入显示字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示属性" prop="显示字段">
              <el-input v-model="form.showProps" placeholder="请输入显示字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单组件路径" prop="componentUrl">
              <el-input v-model="form.componentUrl" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定工作流" prop="workflowDefineId">
              <el-dialog-select bizType="WORKFLOW" v-model="form.workflowDefineId" clearable placeholder="请选择工作流" title="请选择工作流" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="展示列配置" prop="配置展示列">
              <div @click="openColumnConfig">
                <el-input v-model="form.showColumns" readonly ></el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 配置展示列的对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="配置展示列">
      <el-form :model="columnConfig" label-width="80px">
        <!-- 输入列代码的表单项 -->
        <el-form-item label="列代码">
          <el-input v-model="newColumn.code"></el-input>
        </el-form-item>
        <!-- 输入列标题的表单项 -->
        <el-form-item label="列标题">
          <el-input v-model="newColumn.title"></el-input>
        </el-form-item>
        <!-- 添加列的按钮 -->
        <el-form-item>
          <el-button @click="addColumn">添加列</el-button>
        </el-form-item>
      </el-form>
      <!-- 展示已配置列的表格 -->
      <el-table :data="columnConfig" stripe>
        <el-table-column prop="code" label="列代码"></el-table-column>
        <el-table-column prop="title" label="列标题"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 上移按钮，第一行不可用 -->
            <el-button size="small" @click="moveUp(scope.$index)" :disabled="scope.$index === 0">上移</el-button>
            <!-- 下移按钮，最后一行不可用 -->
            <el-button size="small" @click="moveDown(scope.$index)" :disabled="scope.$index === columnConfig.length - 1">下移</el-button>
            <!-- 删除按钮 -->
            <el-button size="small" @click="removeColumn(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveColumns">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listBiz, getBiz, delBiz, addBiz, updateBiz } from "@/api/lc/biz";

export default {
  name: "Biz",
  data() {
    return {
      dialogVisible: false,
      //展示列配置
      columnConfig: [],
      newColumn: {
        code: '',
        title: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务类型表格数据
      bizList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        componentUrl: null,
        masterTableName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "代码不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        masterTableName: [
          { required: true, message: "主表名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "form.idField" (newValue, oldValue) {
      this.form.idProps = this.tranformStr1(newValue);
    },
    "form.showField" (newValue, oldValue) {
      this.form.showProps = this.tranformStr1(newValue);
    }
  },
  methods: {
    //字段转驼峰
    tranformStr1(str){
      var strArr=str.toLowerCase().split('_');
      for(var i=1;i<strArr.length;i++){
        strArr[i]=strArr[i].charAt(0).toUpperCase()+strArr[i].substring(1);
      }
      return strArr.join('');
    },
    // 打开配置展示列的对话框
    openColumnConfig() {
      this.dialogVisible = true;
      try {
        // 解析 showColumns 字符串为数组
        const columnsArray = JSON.parse(this.form.showColumns);
        this.columnConfig = columnsArray;
      } catch (error) {
        console.error('解析 showColumns 时出错:', error);
        this.columnConfig = [];
      }
    },
    // 添加新的列配置
    addColumn() {
      if (this.newColumn.code && this.newColumn.title) {
        this.columnConfig.push({
          code: this.newColumn.code,
          title: this.newColumn.title
        });
        this.newColumn = {
          code: '',
          title: ''
        };
      }
    },
    // 删除指定索引的列配置
    removeColumn(index) {
      this.columnConfig.splice(index, 1);
    },
    // 保存配置并关闭对话框
    saveColumns() {
      this.form.showColumns = JSON.stringify(this.columnConfig);
      this.dialogVisible = false;
    },
    // 将指定索引的列配置上移
    moveUp(index) {
      if (index > 0) {
        const temp = this.columnConfig[index];
        this.columnConfig[index] = this.columnConfig[index - 1];
        this.columnConfig[index - 1] = temp;
      }
    },
    // 将指定索引的列配置下移
    moveDown(index) {
      if (index < this.columnConfig.length - 1) {
        const temp = this.columnConfig[index];
        this.columnConfig[index] = this.columnConfig[index + 1];
        this.columnConfig[index + 1] = temp;
      }
    },

    /** 查询业务类型列表 */
    getList() {
      this.loading = true;
      listBiz(this.queryParams).then(response => {
        this.bizList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        title: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        userId: null,
        deptId: null,
        workflowStatus: null,
        submitUserId: null,
        submitDeptId: null,
        submitTime: null,
        lastAuditTime: null,
        lastAuditUserId: null,
        componentUrl: null,
        masterTableName: null,
        workflowDefineId: null,
        idField: 'id',
        idProps: 'id',
        showField: 'title',
        showProps: 'title',
        showColumns: '[{"code":"code","title":"工作流ID"},{"code":"title","title":"工作流名称"}]'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业务类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBiz(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业务类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBiz(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiz(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除业务类型编号为"' + ids + '"的数据项？').then(function() {
        return delBiz(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lc/biz/export', {
        ...this.queryParams
      }, `biz_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
